package com.hmdp.utils;

import cn.hutool.core.codec.PunyCode;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class RedisIdWorker {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 开始时间戳,2023.1.1 00:00:00
     */
    private static final long BEGIN_TIMESTAMP = 1672531200L;

    public static final int COUNT_BITS=32;

    public long createId(String key){
        // 1.生成时间戳,距离纪元的秒值差
        LocalDateTime now = LocalDateTime.now();
        long head=now.toEpochSecond(ZoneOffset.UTC)-BEGIN_TIMESTAMP;

        //2.生成自增序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //对于redis，key不存在时，默认初始化0，然后自增；如果存在就在基础上自增
        Long tail = stringRedisTemplate.opsForValue().increment(key + date);

        return head <<COUNT_BITS | tail;
    }



}


